package com.zhonghui.common.eshopService.impl;

import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eshop.service.Impl.BaseServiceImpl;
import com.zhonghui.common.eshopDozer.config.IGenerator;
import com.zhonghui.common.eshopEnum.ShopCommonEnum;
import com.zhonghui.common.eshopMapper.StoreSeckillMapper;
import com.zhonghui.common.eshopService.StoreSeckillService;
import com.zhonghui.common.eshopVo.StoreSeckillQueryVo;
import com.zhonghui.modlules.product.eshopDomain.StoreSeckill;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional(
        propagation = Propagation.SUPPORTS,
        readOnly = true,
        rollbackFor = {Exception.class}
)
public class StoreSeckillServiceImpl extends BaseServiceImpl<StoreSeckillMapper, StoreSeckill> implements StoreSeckillService {
    @Autowired
    private IGenerator generator;
    @Autowired
    private StoreSeckillMapper storeSeckillMapper;

    public List<StoreSeckillQueryVo> getList(int page, int limit) {
        Date nowTime = new Date();
        Page<StoreSeckill> pageModel = new Page((long)page, (long)limit);
        LambdaQueryWrapper<StoreSeckill> wrapper = new LambdaQueryWrapper();
        wrapper.eq(StoreSeckill::getStatus, ShopCommonEnum.IS_STATUS_1.getValue())
                .eq(StoreSeckill::getIsHot, 1).le( StoreSeckill::getStartTime, nowTime )
                .ge(StoreSeckill::getStopTime, nowTime).orderByDesc(StoreSeckill::getSort);
        List<StoreSeckillQueryVo> storeSeckillQueryVos = this.generator.convert(((Page)this.storeSeckillMapper.selectPage(pageModel, wrapper)).getRecords(), StoreSeckillQueryVo.class);
        storeSeckillQueryVos.forEach((item) -> {
            Integer sum = item.getSales() + item.getStock();
            item.setPercent( NumberUtil.round(NumberUtil.mul(NumberUtil.div(item.getSales(), sum), 100), 0).intValue());
        });
        return storeSeckillQueryVos;
    }
}
